package com.mswyt.utils.msDataSource.register;

import com.mswyt.utils.base.MsAopUtils;
import com.mswyt.utils.base.MsEmptyUtils;
import com.mswyt.utils.config.constants.ApplicationConstant;
import com.mswyt.utils.msDataSource.annotation.MsDataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @ClassName: MsDataSourceAop
 * @Description: 拦截
 */
@Aspect
@Component
public class MsDataSourceAop {
    @Pointcut("@annotation(com.mswyt.utils.msDataSource.annotation.MsDataSource)")
    public void dsPointCut() {

    }

    @Around("dsPointCut()")
    public Object switchDataSource(ProceedingJoinPoint joinPoint) throws Throwable {
        //如果未开启多数据源配置，直接返回
        if (!"true".equals(ApplicationConstant.msDbOpenDataSource)) {
            return joinPoint.proceed();
        }
        MsDataSource annotation = MsAopUtils.getAnnotation(joinPoint, MsDataSource.class);
        //切换数据源
        if (annotation != null && MsEmptyUtils.isNotEmpty(annotation.value())) {
            MsSwitchDataSource.setDataSource(annotation.value());
        }
        //执行方法
        Object proceed = joinPoint.proceed();
        //执行结束重新切换到默认数据源
        MsSwitchDataSource.clearDataSource();
        return proceed;
    }

}
